var express = require('express');
var router = express.Router();
var nodemailer = require("nodemailer");
var path = require('path');
var smtpTransport = require('nodemailer-smtp-transport');
var sqlite3 = require('sqlite3').verbose();
var settingConfig = {
    smtp : 'smtp.163.com',
    mailFrom : 'weblanl@163.com',
    mailPwd : 'KTDYDFLIDWYWMASB',
    secret : 'weblanl_123'
};//require('../config/settingConfig.js');//解析参数

var smtp = settingConfig["smtp"];
//var mailFrom = Buffer.from(settingConfig["mailFrom"]).toString('base64');
//var mailPwd = Buffer.from(settingConfig["mailPwd"]).toString('base64');
var mailFrom = settingConfig["mailFrom"];
var mailPwd = settingConfig["mailPwd"];

function emailTo(email,subject,text,html,callback) {
// 开启一个 SMTP 连接池
    var transporter = nodemailer.createTransport(smtpTransport({
        host: smtp,//主机
        secure: true, // 使用 SSL
        secureConnection: true, // 使用 SSL
        port: 465, // SMTP 端口
        auth: {
            type:'login',
            user: mailFrom,
            pass: mailPwd //授权码,通过QQ获取  

        }
    }));
    var mailOptions = {
        from: mailFrom, // 发送者  
        to: email, // 接受者,可以同时发送多个,以逗号隔开  
        subject: subject, // 标题  
    };    
    mailOptions.text =text;// 文本  30 
    var result = {
        httpCode: 200,
        message: '发送成功!',
        data: [],
    }
    try {
        transporter.sendMail(mailOptions, function (err, info) {
            if (err) {
                result.httpCode = 500;
                result.message = err;
                callback(result);
                return;
            }
            callback(result);
        });
        transporter.close(); // 如果没用，关闭连接池
    } catch (err) {
        result.httpCode = 500;
        result.message = err;
        callback(result);
    }
    
}

/* GET users listing. */
router.get('/', function(req, res, next) {

    //通过username查询数据库得到email地址
    var db=new sqlite3.Database(path.join(__dirname, "../db/userInfo.db3"));
    const username = req.query.username;
    var userEmail = "";
    try{
        db.serialize(function() {
            //sqlStr = "CREATE TABLE IF NOT EXISTS TBL_meta (ID varchar2(255), label varchar2(255))"
            sqlStr = "SELECT email from userInfo where userName='"+username+"'";
            db.all(sqlStr, function(err, rows) {
                if(rows[0]==undefined)
                    res.send('0');
                else{
                    // console.log(rows[0].email);
                    userEmail=rows[0].email;
                    //产生4位随机数字保存在session   
                    let code=Math.floor(Math.random()*9000)+1000;
                    // res.session=code;
                    emailTo("weblanl@163.com,"+userEmail,"identify",""+code,"",function(data){
                    // console.log(res.session);
                    req.session.captcha = code; 
                    // console.log(req.session); //0xtg 生成的验证码
                    //保存到cookie 方便前端调用验证
                    res.cookie('captcha', req.session); 
                    res.setHeader('Content-Type', 'image/svg+xml');
                    res.write(String(code));
                    res.end();
                    // res.send('1');
                })
                // res.send('respond with a resource');
                }
            });

      });
    }catch(ex){
        console.log(ex);
    }
});

module.exports = router;

